// Serveur de gestion du dispatch des coordonées des pions sur la carte
//

//CONFIG
//var HOST = "127.0.0.1";
//var PORT = 8124;

var SETTINGS_ANTINODE="./settings.antinode.json";
var SETTINGS_WEBSOCKET="./settings.ws.json";

var http = require('http');
var ws = require("ws");
var fs = require("fs");
var antinode = require("antinode");
var log = console.log;

function getSettings(filename, data, err){
	var settings = {};
	if (err) {
		log('No '+filename+' found. Using default settings');
	} else {
		try {
			settings = JSON.parse(data.toString('utf8',0,data.length));
		} catch (e) {
			log('Error parsing '+filename+': '+e);
			process.exit(1);
		}
	}
	return settings;
}

fs.readFile(SETTINGS_ANTINODE, function(err, data) {
	antinode.start(getSettings(SETTINGS_ANTINODE, data, err));
	log("Antinode server RUNNING");
});

fs.readFile('settings.ws.json',function(err,data){
	var settings = getSettings(SETTINGS_WEBSOCKET, data, err);
	
	//Classic web server >> Not used here
	var httpServer = http.createServer(function (req, res) {});

	//Web socket web server
	var wsServer = ws.createServer({debug:true},httpServer);

	wsServer.addListener("listening", function(){
		log("Listening...");
	});

	wsServer.addListener("connection", function(conn){
		//wsServer.send(conn.id,"{id:"+ conn.id+"}");
		conn.pingInterval = setInterval(function(){
						try{
							wsServer.send(conn.id,"ping");
						}
						catch(e){
							//ignore
						}
					},2000);
		conn.broadcast('["'+conn.id+'",[0,0]]');
		conn.addListener("message", function(message){
			log("Message: " + message);
			if(message=="pong"){
				//IGNORE!
			}
			else{
				var msgAsJSON = JSON.parse(message);
				if(msgAsJSON.length==2){
					conn.broadcast('["'+conn.id+'",'+message+']');
				}
				else {
					log("Bad request!!");
				}
			}
		});
	});

	wsServer.addListener("close", function(conn){
		log("Closing...");
		clearInterval(conn.pingInterval);
		//conn.broadcast("<"+conn.id+"> disconnected");
	});

	wsServer.listen(settings['port'], settings['host']);

	log('Web socket server RUNNING at http://'+settings['host']+':'+settings['port']);
});

